#用户行为日志生成脚本
import os
import random
import time
import json

from area_code import Areas


def rand_str(length: int):
    source_string = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIKJLMNOPQRSTUVWXYZ"
    r = ""
    for i in range(length):
        r += random.choice(source_string)
    return r


class generator:
    brand_list = ['荣耀', '华为’，‘苹果', 'vivo', '小米', 'oppo', '三星', '魅族', '中兴', '联想', '一加', 'realme',
                  'HTC', 'LG', '诺基亚']
    @classmethod
    def gen_view_log(cls, num:int, timeRange, target:str):
        """
        生成浏览日志
        :param num:
        :param timeRange:
        :param target: 保存文件路径
        :return:
        """
        for v in range(num):
            brand = random.choice(cls.brand_list)
            uid = random.randint(1,1000)
            timeStamp = random.randint(timeRange[0], timeRange[1])
            tmp = {
                "common": { # 用户设备环境信息，同上
                    "ar": Areas.get_random_area_code(), #用户地区编码  00~
                    "ba": brand, #品牌
                    "ch": "渠道%d" % (random.randint(1,10)), #app 渠道  1~10
                    "is_new": "%d" % (int(random.randint(0,10) / 10)), #是否首日使用
                    "md": "%s 型号%d" % (brand, random.randint(1,20)), #用户手机型号
                    "mid": str(uid), #设备型号
                    "os": random.choice(['Android','IOS','Harmony']), #操作系统
                    "sid": rand_str(20), #会话 id
                    "uid": str(uid), #设备型号和uid相同
                    "vc": "v2.1.134" #固定
                },
                "actions": [{ #-- 动作(事件)
                    "action_id": random.choice(["favor_add","review_add","common_add","cart_add"]), # 动作id
                    "item": random.randint(1,10000), # 目标id
                    "item_type": random.choice(["course_id","keywords","video_id","chapter_id","coupon_id","order_id","page_id","exam_id"]), # 目标类型
                    "ts": timeStamp # 动作时间戳
                }],
                "displays": [],
                "page": {  # 页面信息
                    "during_time": random.randint(1000,60000),  # 持续时间毫秒
                    "item": random.randint(1,10000),  # 目标id
                    "item_type": random.choice(["course_id","keywords","video_id","chapter_id","coupon_id","order_id","page_id","exam_id"]), # 目标类型
                    "last_page_id": random.choice(["home","course_list","course_detail","chapter_video","cart","order","payment","exam","min"]),
                    "page_id": random.choice(["home","course_list","course_detail","chapter_video","cart","order","payment","exam","min"]),  # 页面ID
                    "from_pos_id": random.randint(1,1000),  # 来源坑位ID
                    "from_pos_seq": random.randint(1,1000),  # 来源坑位序列号
                    "refer_id": random.randint(1,100),  # 外部营销渠道ID
                    "sourceType": "来源%d" % random.randint(1,100)  # 来源类型
                },
                "err":{ #错误
                    "error_code": "0", #错误码 0表示无错误 >0 表示有错误
                    "msg": "***********" #错误信息
                },
                "ts": timeStamp
            }

            for i in range(1, random.randint(1,5)):
                tmp['displays'].append({  # 曝光
                    "displayType": random.choice(['promotion','recommend','query','activity']),  # 曝光类型
                    "item": random.randint(1,10000),  # 曝光对象id
                    "item_type": random.choice(["course_id","keywords","video_id","chapter_id","coupon_id","order_id","page_id","exam_id"]),  # 曝光对象类型
                    "order": i,  # 出现顺序
                    "pos_id": i  # 曝光位置
                })

            with open(target, 'a', encoding="utf8") as f:
                f.write(json.dumps(tmp, ensure_ascii=False) + "\n")

        return

    @classmethod
    def gen_start_log(cls, num:int, timeRange, target:str):
        """
        生成浏览日志
        :param num:
        :param timeRange:
        :param target: 保存文件路径
        :return:
        """
        for v in range(num):
            brand = random.choice(cls.brand_list)
            uid = random.randint(1,1000)

            tmp = {
                "common": { # 用户设备环境信息，同上
                    "ar": Areas.get_random_area_code(), #用户地区编码  00~
                    "ba": brand, #品牌
                    "ch": "渠道%d" % (random.randint(1,10)), #app 渠道  1~10
                    "is_new": "%d" % (int(random.randint(0,10) / 10)), #是否首日使用
                    "md": "%s 型号%d" % (brand, random.randint(1,20)), #用户手机型号
                    "mid": str(uid), #设备型号
                    "os": random.choice(['Android','IOS','Harmony']), #操作系统
                    "sid": rand_str(20), #会话 id
                    "uid": str(uid), #设备型号和uid相同
                    "vc": "v2.1.134" #固定
                },
                "start": {
                    "entry": random.choice(['icon', 'notice', 'install']), #icon 手机图标 notice 通知 install 安装后启动
                    "loading_time": random.randint(1000,5000), #启动加载时间
                    "open_ad_id": random.randint(1,10000), #广告页 ID 1~1000
                    "open_ad_ms": random.randint(5000,10000), # 广告总共播放时间
                    "open_ad_skip_ms": random.randint(1,5000), #用户跳过广告时点
                },
                "err":{ #错误
                    "error_code": "0", #错误码 0表示无错误 >0 表示有错误
                    "msg": "***********" #错误信息
                },
                "ts": random.randint(timeRange[0], timeRange[1])
            }
            with open(target, 'a', encoding="utf8") as f:
                f.write(json.dumps(tmp, ensure_ascii=False) + "\n")


    @classmethod
    def gen_video_log(cls, num:int, timeRange, target:str):
        """
        生成视频日志
        :param num:
        :param timeRange:
        :param target: 保存文件路径
        :return:
        """


        for v in range(num):
            brand = random.choice(cls.brand_list)
            uid = random.randint(1,1000)

            tmp = {
                "common": { # 用户设备环境信息，同上
                    "ar": Areas.get_random_area_code(), #用户地区编码  00~
                    "ba": brand, #品牌
                    "ch": "渠道%d" % (random.randint(1,10)), #app 渠道  1~10
                    "is_new": "%d" % (int(random.randint(0,10) / 10)), #是否首日使用
                    "md": "%s 型号%d" % (brand, random.randint(1,20)), #用户手机型号
                    "mid": str(uid), #设备型号
                    "os": random.choice(['Android','IOS','Harmony']), #操作系统
                    "sid": rand_str(20), #会话 id
                    "uid": str(uid), #设备型号和uid相同
                    "vc": "v2.1.134" #固定
                },
                "appVideo": {
                    "play_sec": random.randint(1,600), #视频播放时长
                    "position_sec": random.randint(1, 100), #播放进度百分比
                    "video_id": random.randint(1,10000) #视频ID
                },
                "err":{ #错误
                    "error_code": "0", #错误码 0表示无错误 >0 表示有错误
                    "msg": "***********" #错误信息
                },
                "ts": random.randint(timeRange[0], timeRange[1])
            }
            with open(target, 'a', encoding="utf8") as f:
                f.write(json.dumps(tmp, ensure_ascii=False) + "\n")

ROOT_PATH = os.path.dirname(os.path.dirname(os.path.abspath(os.path.join(__file__, '.'))))
if __name__ == '__main__':
    start_time = int(time.time()*1000) - 24*3600 * 60 #过去60天
    end_time = int(time.time()*1000)
    time_range = [start_time, end_time]
    generator.gen_view_log(10, time_range, ROOT_PATH+'/test/user_action_logs/view.log')
    generator.gen_start_log(10, time_range, ROOT_PATH+'/test/user_action_logs/start.log')
    generator.gen_video_log(10, time_range, ROOT_PATH+'/test/user_action_logs/video.log')